package com.jn.rxjava.views;

import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.DialogFragment;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.jn.rxjava.R;
import com.jn.rxjava.entity.BingResponse.BingImage;

import java.io.FileOutputStream;
import java.io.OutputStream;

public class ImageDialogFragment extends DialogFragment {

    private static final int RC_WRITE_EXTERNAL_STORAGE = 123;
    private BingImage image;
    private ImageView imageView;

    public static ImageDialogFragment newInstance(BingImage image) {
        ImageDialogFragment fragment = new ImageDialogFragment();
        Bundle args = new Bundle();
        args.putParcelable("image", image);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            image = getArguments().getParcelable("image");
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_image_dialog, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        imageView = view.findViewById(R.id.image_view);

        Glide.with(this)
                .load(image.getUrl())
                .into(imageView);

        imageView.setOnLongClickListener(v -> {
            showSaveConfirmationDialog();
            return true;
        });
    }

    private void showSaveConfirmationDialog() {
        new AlertDialog.Builder(requireContext())
                .setTitle("保存图片")
                .setMessage("您确定要保存这张图片吗？")
                .setPositiveButton("保存", (dialog, which) -> {
                    requestStoragePermission();
                })
                .setNegativeButton("取消", null)
                .create()
                .show();
    }

    private void requestStoragePermission() {
        if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            saveImageToGallery();
        } else {
            ActivityCompat.requestPermissions(requireActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, RC_WRITE_EXTERNAL_STORAGE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == RC_WRITE_EXTERNAL_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                saveImageToGallery();
            } else {
                Toast.makeText(requireContext(), "权限被拒绝，无法保存图片", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void saveImageToGallery() {
        Glide.with(this)
                .asBitmap()
                .load(image.getUrl())
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        Log.d("ImageDialogFragment9999999999999999999999999", "Bitmap loaded successfully.");
                        saveBitmap(resource);
                    }

                    @Override
                    public void onLoadFailed(@Nullable Drawable errorDrawable) {
                        super.onLoadFailed(errorDrawable);
                        Log.e("ImageDialogFragment999999999999999999999999999999", "Failed to load image.");
                        Toast.makeText(requireContext(), "加载图片失败", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {
                    }
                });
    }

    private void saveBitmap(Bitmap bitmap) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, System.currentTimeMillis() + ".jpg");
        contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, "DCIM");

        ContentResolver contentResolver = requireContext().getContentResolver();
        Uri uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);

        if (uri == null) {
            Log.e("ImageDialogFragment666666666666666666666666", "Failed to insert image into media store.");
            Toast.makeText(requireContext(), "保存失败", Toast.LENGTH_SHORT).show();
            return;
        }

        try (OutputStream outputStream = contentResolver.openOutputStream(uri)) {
            if (outputStream == null) {
                Log.e("ImageDialogFragment666666666666666666666666", "Failed to open output stream.");
                Toast.makeText(requireContext(), "保存失败", Toast.LENGTH_SHORT).show();
                return;
            }
            boolean isSaved = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            if (isSaved) {
                Toast.makeText(requireContext(), "图片已保存到相册", Toast.LENGTH_SHORT).show();
                Log.d("ImageDialogFragment6666666666666666666666666666", "Image saved successfully.");
            } else {
                Log.e("ImageDialogFragment66666666666666666666666666666666666", "Failed to compress and save image.");
                Toast.makeText(requireContext(), "保存失败", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("ImageDialogFragment666666666666666666666666666666666666", "Exception while saving image: " + e.getMessage());
            Toast.makeText(requireContext(), "保存失败", Toast.LENGTH_SHORT).show();
        }
    }
}